package com.gcloud.mesh.utils;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CmdExecuteUtil {

	public static String runAndGetValue(String[] command) {
        String result = null;
        Process proc = null;
        try {
            String commandString = "";
            for (String part : command) {
                commandString += part + " ";
            }
            log.debug("Running command: " + commandString);
            Runtime rt = Runtime.getRuntime();
            proc = rt.exec(command);
            StreamConsumer error = new StreamConsumer(proc.getErrorStream());
            StreamConsumer output = new StreamConsumer(proc.getInputStream());
            error.start();
            output.start();
            int returnValue = proc.waitFor();
            output.join();
            if (returnValue != 0) {
                result = error.getReturnValue();
            }

            if (StringUtils.isBlank(result)) {
                result = output.getReturnValue();
            }
        } catch (Exception t) {
            log.error("Running command error :", t.getMessage());
        } finally {
            if (proc != null)
                proc.destroy();
        }
        return result;
    }
    
    public static String runAndGetValueWithPipe(String[] command) {       
        String subCommand = StringUtils.join(command, " ");
        String[] execCmds = {"sh", "-c",  subCommand};
        return CmdExecuteUtil.runAndGetValue(execCmds);
    }
}
